package misc;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.ArrayList;


public class ShellEnv implements Env {

	private ArrayList<Object> m_EnvProperties;
	
	public ShellEnv() {
		m_EnvProperties = new ArrayList<Object>();
		m_EnvProperties.add("/bin/bash");
		m_EnvProperties.add("-c");
	}
	
	public String exec (String command, boolean wait) {
		
		byte[] input;
		Process process;
		BufferedInputStream is;
		StringBuffer buffer;
		
		process = null;
		buffer = null;
	   
		try {	
			process = Runtime.getRuntime().exec(new String[]{
							(String) m_EnvProperties.get(0), // /bin/bash
							(String) m_EnvProperties.get(1), // -c
							command});
		
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (wait) {
			
			try {
				process.waitFor();
				is = new BufferedInputStream(process.getInputStream());
				buffer = new StringBuffer();
				input = new byte[512];
				
				while (is.read(input) != -1) {
					buffer.append(new String(input));
				}
			
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				e.printStackTrace();
				
			} catch (IOException e) {
				e.printStackTrace();
			
			} finally {
				
				try {
					process.getInputStream().close();
					process.getErrorStream().close();
					process.getOutputStream().close();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			return buffer.toString();
		}
		
		return null;
	}
}
